package fr.contest.eureka.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import com.google.inject.Singleton;

/**
 * Server used for devices player communication.
 * @author Romain
 *
 */
@Singleton
public class GameServer 
{
	/** Server port for network in-game communication. */
	public static final int SERVER_GAME_PORT = 5555;
	
	/** Server port for players discovering communication. */
	public static final int SERVER_DISCOVERING_PORT = 5554;
	
	/** Running state of server. */
	private boolean isServerRunning = false;
	
	private ServerSocket mServerDiscoverSocket;
	
	/**
	 * Start the server.
	 * @return true if the server has started, false either
	 */
	public boolean startServer()
	{
		if(!isServerRunning)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	public void stopServer()
	{
		isServerRunning = false;
	}
	
	class ServerDiscoverThread implements Runnable {

		public void run() {
			Socket socket = null;
			try {
				mServerDiscoverSocket = new ServerSocket(SERVER_DISCOVERING_PORT);
			} catch (IOException e) {
				e.printStackTrace();
			}
			while (!Thread.currentThread().isInterrupted()) {

				try {

					socket = mServerDiscoverSocket.accept();

					CommunicationThread commThread = new CommunicationThread(socket);
					new Thread(commThread).start();

				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	class CommunicationThread implements Runnable {

		private Socket clientSocket;

		private BufferedReader input;

		public CommunicationThread(Socket clientSocket) {

			this.clientSocket = clientSocket;

			try {

				this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));

			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		public void run() {

			while (!Thread.currentThread().isInterrupted()) {

				try {

					String read = input.readLine();

				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

}
